<template>
  <mis-drag-dialog
    ref="misDragDialogRef"
    :title="title"
    :visible.sync="showFlag"
    :width="width"
    :top="top"
    :body-padding="bodyPadding"
    :before-close="handleBeforeClose"
    append-to-body
  >
    <dynamicComp ref="dynamicCompRef" v-bind="componentProps"></dynamicComp>

    <template v-if="showFooter" #footer>
      <el-button size="small" @click="onCancel">取消</el-button>
      <el-button type="primary" size="small" :loading="submitLoading" @click="onSave">保存</el-button>
    </template>
  </mis-drag-dialog>
</template>

<script>
export default {
  name: 'dynamic-drag-dialog',
  data() {
    return {
      submitLoading: false,
      showFlag: false,
      showFooter: false,
      width: '720px',
      top: '15vh',
      bodyPadding: '',
      title: '',
      componentProps: {},
    };
  },

  methods: {
    /**
     * 弹框关闭钩子函数
     * @param done
     */
    handleBeforeClose(done) {
      this.onCancel();
      done();
    },

    /**
     * 显示
     * @param cb
     * @return {Promise<unknown>}
     */
    show(cb) {
      this.showFlag = true;
      typeof cb === 'function' && cb.call(this, this);
      return new Promise((resolve, reject) => {
        this.reject = reject;
        this.resolve = resolve;
      });
    },

    /**
     * 取消
     */
    onCancel() {
      this.handleDynamicCompFn('cancel', result => {
        this.reject(result);
        this.hide();
      });
    },

    /**
     * 确认保存
     */
    onSave() {
      this.submitLoading = true;
      this.handleDynamicCompFn('confirm', result => {
        this.submitLoading = false;
        this.resolve(result);
        this.hide();
      });
    },

    /**
     * 隐藏后删除元素
     */
    hide() {
      this.showFlag = false;
      document.body.removeChild(this.$el);
      this.$destroy();
    },

    /**
     * 执行动态添加的组件内部事件，如：保存、取消等事件
     * @param { string } eventType 事件类型: cancel-取消； save-保存
     * @param { function } cb 回调函数
     */
    handleDynamicCompFn(eventType, cb) {
      if (!this.$refs.dynamicCompRef) {
        new Error('动态导入的组件未加载完成或无效');
      }
      const compRef = this.$refs.dynamicCompRef;
      if (eventType === 'confirm') {
        compRef.handleSave && compRef.handleSave(cb);
      } else if (eventType === 'cancel') {
        compRef.handleCancel && compRef.handleCancel(cb);
      }
    },
  },
};
</script>

<style scoped lang="scss"></style>
